﻿using Colorful.CMS.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Colorful.Database;

namespace Colorful.CMS
{
    public class APIAuthFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.Filters.Any(a => a is Microsoft.AspNetCore.Mvc.Authorization.AllowAnonymousFilter))
            {
                var request = context.HttpContext.Request;
                if (request.Path.StartsWithSegments("/api/cms"))
                {
                    var appkey = request.Get("appkey");
                    if (string.IsNullOrEmpty(appkey) || !APIHelper.CheckSignature(request, GetAppSecret(appkey)))
                    {
                        context.Result = new ContentResult()
                        {
                            Content = "签名错误！",
                            ContentType = "text/html",
                            StatusCode = 200
                        };
                    }
                }
            }
        }

        private string GetAppSecret(string appKey)
        {
            using (var db = DbHelper.GetDb())
            {
                return db.Members.Where(a => a.AppKey == appKey).Select(a => a.AppSecret).FirstOrDefault();
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {

        }
    }
}
